#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
获取访问令牌接口
"""

import os
from flask import Blueprint, request, jsonify, current_app
from utils.logger import get_logger

gettoken_bp = Blueprint('gettoken', __name__)
logger = get_logger(__name__)


@gettoken_bp.route('/cgi-bin/gettoken', methods=['GET'])
def get_token():
    """获取企业微信访问令牌 - Mock版本，直接返回成功"""
    try:
        # 获取请求参数（仅用于日志记录）
        corpid = request.args.get('corpid', 'unknown')
        corpsecret = request.args.get('corpsecret', 'unknown')
        
        logger.info(f"获取访问令牌请求 - corpid: {corpid}")
        
        # 获取数据管理器
        data_manager = current_app.data_manager
        
        # 直接创建访问令牌，不验证参数
        access_token = data_manager.create_token(corpid, corpsecret)
        expires_in = int(os.getenv('MOCK_TOKEN_EXPIRES', '7200'))
        
        # 更新统计信息
        data_manager.update_stats(success=True)
        
        logger.info(f"访问令牌创建成功 - token: {access_token[:20]}...")
        
        return jsonify({
            "errcode": 0,
            "errmsg": "ok",
            "access_token": access_token,
            "expires_in": expires_in
        })
        
    except Exception as e:
        logger.error(f"获取访问令牌失败: {e}")
        data_manager = current_app.data_manager
        data_manager.update_stats(success=False)
        
        return jsonify({
            "errcode": 500,
            "errmsg": "internal error"
        }), 500
